/*
 * AjaxAuthenticationFailureHandler.java
 *
 * Copyright 2012 the original author or authors(ninglong).
 *
 * Licensed under the org.geek.login.service.impl, Version 1.0 (the "License");
 *
 */
package org.geek.app.login.service.impl;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

/**
 * <p>登录失败处理</p>
 * @author ninglong bhd2973@qq.com
 * @version V1.0
 */
public class AjaxAuthenticationFailureHandler implements AuthenticationFailureHandler {
	
	private Logger logger = LoggerFactory.getLogger(AjaxAuthenticationFailureHandler.class);
	
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException exception)
			throws IOException, ServletException {
		 String msg = exception.getMessage();
		 response.setContentType("text/html;charset=UTF-8");
		 PrintWriter out = response.getWriter();
		 
		 if("UserDetailsService returned null, which is an interface contract violation".equals(msg)){
			 msg ="用户不存,请核对后再登录!";
		 }else if("Bad credentials".equals(msg)){
			 msg = "密码不正确!";
		 }else if("Authentication method not supported: GET".equals(msg)){
			 response.sendRedirect("login.jsp");
			 return;
		 }else if("Transaction rolled back because it has been marked as rollback-only".equals(msg)){
			 msg = "数据库异常!";
		 }
		 
		 out.write("{success:false,error:'"+msg+"'}");
		 out.close();
		 if(logger.isDebugEnabled()){
			 logger.debug("登录失败,原因:"+msg);
		 }
	}
}
